package org.microdream.easy.deploy.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.apache.commons.collections.CollectionUtils;
import org.microdream.easy.deploy.dao.DServerRepository;
import org.microdream.easy.deploy.po.CachePo;
import org.microdream.easy.deploy.po.DServer;
import org.microdream.easy.deploy.po.DServerAuth;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import ice.server.comm.BaseServiceImpl;
import ice.server.comm.CommRepository;
import ice.server.comm.ParamBulider;
import ice.tool.ResultMap;

@Service
public class DServerService extends BaseServiceImpl<DServer, Integer> {
	
	@Resource
	private DServerRepository dServerRepository;
	
	@Resource
	private DServerAuthService dServerAuthService;

	@Override
	public CommRepository<DServer, Integer> getRepository() {
		return dServerRepository;
	}

	@Override
	public Integer getIdenty(DServer t) {
		return t.getId();
	}
	
	public Page<DServer> queryPage(Map<String, Object> param) {
		Page<DServer> p = this.findPage(param);
		// 处理字典
		for(DServer s : p.getContent()) {
			processDic(s);
		}
		return p;
	}
	
	private void processDic(DServer s) {
		s.set("showLinkType", CachePo.getName("link_type", s.getLinkType()));
		s.set("showServerType", CachePo.getName("server_type", s.getServerType()));
	}
	
	/**
	 * 新增服务器
	 * @param s
	 * @return
	 */
	@Transactional(rollbackOn=Exception.class)
	public Map<String, Object> add(DServer s) {
		this.save(s);
		List<DServerAuth> l = new ArrayList<>();
		if(!CollectionUtils.isEmpty(s.getUsername())) {
			for (int i = 0; i < s.getUsername().size(); i++) {
				DServerAuth sa = new DServerAuth();
				sa.setServerCode(s.getServerCode());
				sa.setUsername(s.getUsername().get(i));
				sa.setUserpwd(s.getUserpwd().get(i));
				l.add(sa);
			}
		}
		dServerAuthService.save(l);
		return ResultMap.build().add(true).get();
	}
	
	/**
	 * 删除服务器信息
	 * @param ids
	 * @return
	 */
	@Transactional(rollbackOn = Exception.class)
	public Map<String, Object> deletServer(int[] ids) {
		boolean someFail = false;
		//遍历删除
		for (int id : ids) {
			// 判断服务器是否在使用中
			if(isUsed(id)) {
				someFail = true;
				continue;
			}
			// 删除账号信息
			deleteAuth(id);
			this.delete(id);
		}
		return someFail ? ResultMap.build().delete(true).message("部分服务器正在被使用，无法删除！").get() : 
			ResultMap.build().delete(true).get();
	}
	
	private void deleteAuth(int id) {
		DServer s = get(id);
		dServerAuthService.delete(ParamBulider.build().addEqual("serverCode", s.getServerCode()).get());
	}
	
	private boolean isUsed(int id) {
		//TODO: 判断部署实例使用引用了此服务器
		return false;
	}

}
